﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using SXFramWork.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.API
{
    /// <summary>
    /// 权限验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public class PermissionAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //AllowAnonymous
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(AllowAnonymousAttribute)))
                return;

            //登录验证
            var login = context.HttpContext.RequestServices.GetService<ILoginInfo>();
            if (login == null || !(login?.UserId.Length> 0))
            {
                context.Result = new ChallengeResult();
                return;
            }

            //排除通用接口 登录就可以访问的接口 不需要授权
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(CommonAttribute)))
                return;

            //超级管理员不进行权限验证

            //权限验证
            var httpMethod =context.HttpContext.Request.Method;
            var handler = context.HttpContext.RequestServices.GetService<IPermissionHandler>();

            if (!await handler.ValidateAsync(context.ActionDescriptor.RouteValues, httpMethod))
            {
                //无权限
                context.Result = new ForbidResult();
            }

        }
    }
}
